package com.example.ymm.modules1.controller.user;

import com.example.ymm.exception.YmException;
import com.example.ymm.model.CommonResult;
import com.example.ymm.modules1.controller.BaseController;
import com.example.ymm.modules1.entity.hl.ex.*;
import com.example.ymm.modules1.query.hl.ex.ExUserAnserQueryCriteria;
import com.example.ymm.modules1.query.hl.ex.ExUserPaperQueryCriteria;
import com.example.ymm.modules1.service.dto.heng.ex.*;
import com.example.ymm.modules1.service.hl.ex.*;
import com.example.ymm.util.UtilValidate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/hl/user/ex")
@Tag(name= "用户端 考试管理")
@Slf4j
@CrossOrigin
public class UserExController extends BaseController {

    @Autowired
    ExPublishPaperService exPublishPaperService;
    @Autowired
    ExUserPaperService exUserPaperService;
    @Autowired
    ExUserAnserService exUserAnserService;
    @Autowired
    ExTeamUserService exTeamUserService;
    @Autowired
    ExTeamService exTeamService;
    @Autowired
    private ExPaperService exPaperService;


    @Operation(summary= "手动通知交卷")
    @PostMapping("/userSubQuestions")
    public CommonResult sysNotifySubmit(@RequestBody ExPublishPaper publishPaper) {
        try{

            String userName = getUserName();
            ExPublishPaper samplePaper = exPublishPaperService.getSamplePaper(publishPaper.getPublishPaperId());
            ExPaper paper = exPaperService.getById(samplePaper.getPaperId());
            if(UtilValidate.isEmpty(paper)){
                return CommonResult.error("查找不到试卷信息!");
            }
            Integer ruleType = paper.getRuleType();
            ExPublishGroup startGroup = publishPaper.getStartGroup();


            ExUserAnserQueryCriteria criteria=new ExUserAnserQueryCriteria();
            criteria.setUserName(userName);
            criteria.setPublishPaperId(startGroup.getPublishPaperId());
            criteria.setPublishGroupId(startGroup.getPublishGroupId());
            List<ExUserAnser> exUserAnsers = exUserAnserService.queryAll(criteria);
            if(UtilValidate.isNotEmpty(exUserAnsers)){
                throw new YmException("你已经提交过该模块的题目!");
            }

            GroupOneResultDto groupOneResultDto = new GroupOneResultDto();
            groupOneResultDto.setSubmit(true);
            //计分规则：1 区分团队 0 普通计分
            if(ruleType==1){
                UserAnserDto  userAnserDto = exPublishPaperService.sysSubmitPaper(publishPaper, userName);
                groupOneResultDto.setQuestionType("选择题");
                if(userAnserDto.isPaperOver()){
                    groupOneResultDto.setPaperOver(true);
                }
                groupOneResultDto.setResult1(userAnserDto);
            }else{
                log.info("---面试交卷");
                //面试交卷
                GroupOneResultDto oneResultDto = exPublishPaperService.userSubmitPaper(publishPaper, userName);
                String questionType = oneResultDto.getQuestionType();
                if("选择题".equals(questionType)){
                    groupOneResultDto.setResult1(oneResultDto.getResult1());
                }else{
                    groupOneResultDto.setResult2(oneResultDto.getResult2());
                }
                if(oneResultDto.isPaperOver()){
                    groupOneResultDto.setPaperOver(true);
                }
                groupOneResultDto.setQuestionType(questionType);
            }
            groupOneResultDto.setRuleType(ruleType);
            return CommonResult.success(groupOneResultDto);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }



    @Operation(summary= "用户加入考场")
    @PostMapping("/userJoinPaper")
    public CommonResult userJoinPaper(@RequestParam String publishPaperId) {
        try{
            String userName = getUserName();
            exPublishPaperService.userJoinPaper(userName, publishPaperId);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Operation(summary= "用户获取试卷信息")
    @PostMapping("/getUserPaper")
    public CommonResult getUserPaper(@RequestParam String publishPaperId) {
        try{
            String userName = getUserName();
            ExPublishPaper userPaper = exPublishPaperService.getUserPaper(userName, publishPaperId);
            return CommonResult.success(userPaper);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Operation(summary= "获取简易版考试信息")
    @PostMapping("/getSamplePaper")
    public CommonResult getSamplePaper(@RequestParam String publishPaperId) {
        try{
            //不带试卷信息
            ExPublishPaper userPaper = exPublishPaperService.getSamplePaper(publishPaperId);
            return CommonResult.success(userPaper);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Operation(summary= "通过publishPaperId获取试卷信息")
    @PostMapping("/getPaperByPublishPaperId")
    public CommonResult getPaperByPublishPaperId(@RequestParam String publishPaperId) {
        try{
            ExPaper exPaper = exPaperService.getByPublishPaperId(publishPaperId);
            return CommonResult.success(exPaper);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Operation(summary= "用户获取试卷分数(团队)")
    @PostMapping("/getUserScore")
    public CommonResult getUserScore(@RequestParam String publishPaperId) {
        try{
            String userName = getUserName();
            UserAnserDetailDto dto= exPublishPaperService.getUserScore(publishPaperId,userName );
            return CommonResult.success(dto);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Operation(summary= "用户获取试卷分数(面试)")
    @PostMapping("/getUserScoreByMainShi")
    public CommonResult getUserScoreByMainShi(@RequestParam String publishPaperId) {
        try{

            List<GroupOneResultDto> list = exUserAnserService.getUserScoreByMainShi(publishPaperId);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }



    @Operation(summary= "我的考试分数记录")
    @PostMapping("/myPaperLogs")
    public CommonResult myPaperLogs() {
        try{
            String userName = getUserName();

            List<MyPaperLog> myPaperLogs = exUserPaperService.myPaperLogs(userName);
            return CommonResult.success(myPaperLogs);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Operation(summary= "试卷答题记录")
    @PostMapping("/getUserAnsers")
    public CommonResult getUserAnsers(@RequestParam String publishPaperId) {
        try{
            String userName = getUserName();
            ExUserAnserQueryCriteria criteria=new ExUserAnserQueryCriteria();
            criteria.setPublishPaperId(publishPaperId);
            criteria.setUserName(userName);
            List<UserAnserView> userAnsers = exUserAnserService.getUserAnsers(criteria);
            return CommonResult.success(userAnsers);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Operation(summary= "所有的排行榜")
    @PostMapping("/getRanks")
    public CommonResult getRanks(@RequestParam String type) {
        try{
            List<RankItemDto> ranks = exTeamUserService.getRanks(type);
            return CommonResult.success(ranks);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Operation(summary= "个人分数")
    @PostMapping("/getUserInfo")
    public CommonResult getUserInfo() {
        try{
            String userName = getUserName();

            ExTeamUser teamUser = exTeamUserService.findByUserName(userName);
            if(UtilValidate.isNotEmpty(teamUser)&&UtilValidate.isNotEmpty(teamUser.getTeamId())){
                ExTeam team = exTeamService.getById(teamUser.getTeamId());
                if(UtilValidate.isNotEmpty(team)){
                    teamUser.setTeamName(team.getName());
                    teamUser.setTeam(team);
                }
            }

            return CommonResult.success(teamUser);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Operation(summary= "试卷个人排行")
    @PostMapping("/getPagerUserRanks")
    public CommonResult getPagerUserRanks(@RequestParam String publishPaperId) {
        try{
//            List<ExTeamUser> exTeamUsers = exTeamUserService.queryAll(null);
            ExUserPaperQueryCriteria criteria=new ExUserPaperQueryCriteria();
            criteria.setPublishPaperId(publishPaperId);
            criteria.setLimit(15);
            List<RankUserItemDto> exTeamUsers = exUserPaperService.getPaperUserRank(criteria);
            return CommonResult.success(exTeamUsers);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Operation(summary= "团队排行")
    @PostMapping("/getPaperTeamRank")
    public CommonResult getPaperTeamRank(@RequestParam String publishPaperId) {
        try{
//            List<ExTeamUser> exTeamUsers = exTeamUserService.queryAll(null);
            ExUserPaperQueryCriteria criteria=new ExUserPaperQueryCriteria();
            criteria.setPublishPaperId(publishPaperId);

            List<RankUserItemDto> exTeamUsers = exUserPaperService.getPaperTeamRank(criteria);
            return CommonResult.success(exTeamUsers);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Operation(summary= "初始化个人排行")
    @PostMapping("/getUsers")
    public CommonResult getUsers() {
        try{
            List<ExTeam> teams = exTeamService.queryAll(null);

            List<ExTeamUser> users = exTeamUserService.queryAll(null);
            users.forEach(user -> {
                teams.forEach(team -> {
                    if(user.getTeamId().equals(team.getTeamId())){
                        user.setTeamName(team.getDeptName());
                    }
                });
                if(user.getUserName().equals("林珊")&&"东莞恒丽".equals(user.getTeamName())){
                    user.setUserName(user.getUserName()+"-东莞");
                }
            });
            return CommonResult.success(users);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Operation(summary= "初始化团队排行")
    @PostMapping("/getTeams")
    public CommonResult getTeams() {
        try{
            List<ExTeam> teams = exTeamService.queryAll(null);
            return CommonResult.success(teams);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

}
